package controllers

/*
Copyright 2021-2025 The k8gb Contributors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Generated by GoLic, for more details see: https://github.com/AbsaOSS/golic
*/

import (
	"context"
	"regexp"
	"strings"

	k8gbv1beta1 "github.com/k8gb-io/k8gb/api/v1beta1"
	corev1 "k8s.io/api/core/v1"
	discov1 "k8s.io/api/discovery/v1"
	"k8s.io/apimachinery/pkg/api/errors"
	"k8s.io/apimachinery/pkg/types"
	"sigs.k8s.io/controller-runtime/pkg/client"
	externaldnsApi "sigs.k8s.io/external-dns/apis/v1alpha1"
)

func (r *GslbReconciler) updateGslbStatus(ctx context.Context, gslb *k8gbv1beta1.Gslb, ep *externaldnsApi.DNSEndpoint) error {

	m.UpdateIngressHostsPerStatusMetric(gslb, gslb.Status.ServiceHealth)

	var err error
	gslb.Status.HealthyRecords, err = r.getHealthyRecords(ctx, gslb)
	if err != nil {
		return err
	}

	gslb.Status.GeoTag = r.Config.ClusterGeoTag
	gslb.Status.Hosts = r.hostsToCSV(gslb)

	m.UpdateHealthyRecordsMetric(gslb, gslb.Status.HealthyRecords)

	m.UpdateEndpointStatus(ep)

	err = r.Status().Update(ctx, gslb)
	return err
}

func (r *GslbReconciler) getServiceHealthStatus(ctx context.Context, gslb *k8gbv1beta1.Gslb) (map[string]k8gbv1beta1.HealthStatus, error) {
	serviceHealth := make(map[string]k8gbv1beta1.HealthStatus)
	for _, server := range gslb.Status.Servers {
		serviceHealth[server.Host] = k8gbv1beta1.NotFound
		for _, svc := range server.Services {
			service := &corev1.Service{}
			finder := client.ObjectKey{
				Namespace: svc.Namespace,
				Name:      svc.Name,
			}
			err := r.Get(ctx, finder, service)
			if err != nil {
				if errors.IsNotFound(err) {
					continue
				}
				return serviceHealth, err
			}

			endpoints := &discov1.EndpointSliceList{}
			err = r.List(ctx, endpoints, client.InNamespace(svc.Namespace), client.MatchingLabels{discov1.LabelServiceName: svc.Name})
			if err != nil {
				return serviceHealth, err
			}

			serviceHealth[server.Host] = k8gbv1beta1.Unhealthy
			if len(endpoints.Items) > 0 {
				if len(endpoints.Items[0].Endpoints) > 0 {
					for _, e := range endpoints.Items[0].Endpoints {
						if len(e.Addresses) > 0 && (e.Conditions.Ready == nil || *e.Conditions.Ready) {
							serviceHealth[server.Host] = k8gbv1beta1.Healthy
						}
					}
				}
			}
		}
	}
	return serviceHealth, nil
}

func (r *GslbReconciler) getHealthyRecords(ctx context.Context, gslb *k8gbv1beta1.Gslb) (map[string][]string, error) {

	dnsEndpoint := &externaldnsApi.DNSEndpoint{}

	nn := types.NamespacedName{
		Name:      gslb.Name,
		Namespace: gslb.Namespace,
	}

	err := r.Get(ctx, nn, dnsEndpoint)
	if err != nil {
		return nil, err
	}

	healthyRecords := make(map[string][]string)

	serviceRegex := regexp.MustCompile("^localtargets")
	for _, endpoint := range dnsEndpoint.Spec.Endpoints {
		local := serviceRegex.Match([]byte(endpoint.DNSName))
		if !local && endpoint.RecordType == "A" {
			if len(endpoint.Targets) > 0 {
				healthyRecords[endpoint.DNSName] = endpoint.Targets
			}
		}
	}

	return healthyRecords, nil
}

func (r *GslbReconciler) hostsToCSV(gslb *k8gbv1beta1.Gslb) string {
	var hosts []string
	for _, server := range gslb.Status.Servers {
		hosts = append(hosts, server.Host)
	}
	return strings.Join(hosts, ", ")
}
